/**
 * @desc   判断安卓系统版本号
 * @return {String} 如4.3.2或者9.0
 */
function getGphoneVersion() {
  const ua = navigator.userAgent.toLowerCase();
  let version = null;

  if (ua.indexOf('android') > 0) {
    const reg = /android [\d._]+/gi;
    const vInfo = ua.match(reg);
    version = `${vInfo}`.replace(/[^0-9|_.]/gi, '').replace(/_/gi, '.');
  }

  return version;
}

/**
 * @desc   判断苹果系统版本号
 * @return {String} 如9.3.2或者9.0
 */
function getIphoneVersion() {
  const ua = navigator.userAgent.toLowerCase();
  let version = null;

  if (ua.indexOf('like mac os x') > 0) {
    const reg = /os [\d._]+/gi;
    const vInfo = ua.match(reg);
    version = `${vInfo}`.replace(/[^0-9|_.]/gi, '').replace(/_/gi, '.');
  }

  return version;
}

/**
 * @description: 获取系统信息
 * @return {Object} sys: 手机系统    version: 系统版本号
 */
function getOS() {
  const SYS = /(iphone)|(mac)|(ipad)/gi.test(navigator.userAgent) ? 'iphone' : 'gphone';
  return {
    sys: SYS,
    version: SYS === 'iphone' ? getIphoneVersion() : getGphoneVersion(),
  };
}

/**
 * @description: 设置页面标题
 * @param {String} str
 */
function setTitle(str) {
  document.title = str;

  if (/hexin/gi.test(navigator.userAgent)) {
    if (navigator.userAgent.toLowerCase().indexOf('android') > 0) {
      window.callNativeHandler('changeWebViewTitle', {
        title: str,
        url: '',
      });
    } else {
      window.callNativeHandler('updateTitleAutomatically');
    }
  }
}

/**
 * @description: 安卓单页应用调用协议解决页面返回 bug
 */
function androidCanBackProtocol() {
  if (/hexin/gi.test(navigator.userAgent) && getOS().sys === 'gphone') {
    const data = {
      method: 'setBrowserField',
      params: {
        isUseDefaultBack: 'true',
      },
    };
    window.callNativeHandler('notifyWebHandleEvent', JSON.stringify(data));
  }
}

/**
 * @description: 动态加载 js 脚本文件
 * @param {String} url
 * @param {Function} nextFn
 */
function loadJs(url, nextFn) {
  const body = document.getElementsByTagName('body')[0];
  const jsNode = document.createElement('script');
  jsNode.setAttribute('type', 'text/javascript');
  jsNode.setAttribute('src', url);

  jsNode.onload = function () {
    nextFn && nextFn();
  };

  body.appendChild(jsNode);
}

/**
 * @description: 验证登录（包含微信授权登录）
 * @param {Function} nextFn
 * 依赖loadJs
 */
function checkLogin(nextFn) {
  if (window.getAppVersion()) {
    if (window.getAccount()) {
      typeof nextFn === 'function' && nextFn();
    } else {
      window.location.href = 'http://eqhexin/changeUser';
    }
  } else {
    if (window.getUserid()) {
      typeof nextFn === 'function' && nextFn();
    } else {
      if (window.wechatLogin) {
        window.wechatLogin(encodeURIComponent(window.location.href));
      } else {
        loadJs('https://upass.10jqka.com.cn/asset/wechatlogin/js/checkwechat.js', function () {
          window.wechatLogin(encodeURIComponent(window.location.href));
        });
      }
    }
  }
}

/**
 * 跳转客户端股票分时页
 * @param {string | number} stockCode 股票代码
 * @param {string | number} marketId 市场id
 */
function jumpToFenShi(stockCode, marketId) {
  location.href = `client://client.html?action=ymtz^webid=2205^stockcode=${stockCode}^marketid=${marketId}`;
}

/**
 * 调用 2804 webview 打开新页面
 * @param {string} url 跳转地址
 */
function jumpBy2804(link) {
  let url = link;
  if (!url || typeof url !== 'string') {
    return;
  }
  if (window.getAppVersion() && url.indexOf('client.html') === -1) {
    !url.startsWith('http') && (url = location.protocol + url);
    window.location.href = `client://client.html?action=ymtz^webid=2804^mode=new^url=${url}`;
  } else {
    window.location.href = url;
  }
}
//客户端视频播放
function clientVideo(url) {
  // function () {}
  window.callNativeHandler('startPlugin', {
    params: {
      url,
      title: '',
    },
    cname: 'com.hexin.videoplayplugin.VideoPlayerActivityWithNoSD',
    pname: 'com.hexin.videoplayplugin',
    scheme: 'thsvideo',
  });
}

//全面屏跳转
function jumpVideoPlayPage(link) {
  const statusBarColor = '#020202';
  let url = '';
  let { protocol } = window.location;
  if (link.indexOf('://') > -1) {
    protocol = '';
  }
  if (window.getAppVersion()) {
    if (window.getPlatform() === 'gphone') {
      // hardwareAccelerated部分机型需要硬件加速播放视频
      url = `client.html?action=ymtz^url=${protocol}${link}^webid=4222^mode=new^hardwareAccelerated=true^userActionForPlayBack=true`;
    } else {
      url = `client.html?action=ymtz^url=${protocol}${link}^webid=2305^showStatusBar=1^userActionForPlayBack=true`;
      if (statusBarColor) {
        url = `client.html?action=ymtz^url=${protocol}${link}^webid=2305^showStatusBar=1^userActionForPlayBack=true^statusBarColor=${statusBarColor}`;
      }
    }
    window.location.href = url;
  } else {
    window.location.href = link;
  }
}

//取查询历史
function getSearchHistory() {
  const userId = window.getUserid();
  let historyLog = window.localStorage.getItem(`${userId}-invest-course`);
  let res = [];
  if (historyLog) {
    historyLog = JSON.parse(historyLog);
    res = historyLog;
  }
  return res;
}

/**
 * @description 改变title颜色
 */
function changeTitleColor(color) {
  window.callNativeHandler('changeWebViewTitleColor', {
    data: {
      status: 'change',
      color,
    },
  });
}
/**
 * @description 预览pdf
 */
function openPdf(param) {
  let { url } = param;
  if (param.url.indexOf('http') === -1) {
    // 避免协议问题，需要补充协议头
    let { protocol } = window.location;
    if (window.location.host.includes('testm')) {
      // 测试环境固定http
      protocol = 'http:';
    }
    url = `${protocol}${param.url}`;
  }
  if (!window.getAppVersion || !window.getAppVersion()) {
    // 微信环境直接打开pdf
    window.location.href = url;
  }
  window.callNativeHandler(
    'HXDownloadFile',
    {
      //需要使用完整的url路径
      url,
      filetype: 'pdf',
      title: param.title,
    },
    () => {
      //不传回调会报错
    }
  );
}
/**
 * @description 预览图片
 */
function openImg(param) {
  const { url } = param;
  const images = [];
  url.forEach(e => {
    // 客户端只接受http类型
    let imgUrl = e;
    if (e.indexOf('http') === -1) {
      imgUrl = `http:${e}`;
    }
    imgUrl.replace('https:', 'http:');
    images.push(imgUrl);
  });
  window.callNativeHandler(
    'displayImageThumbnail',
    {
      // 显示的图片可以切换位置
      currentIndex: param.index ? param.index : 0,
      originImages: [...images],
      detailImages: [...images],
    },
    () => {
      //不传回调会报错
    }
  );
}

function setTitleColor(
  color = {
    white: '#000000',
    black: '#000000',
  }
) {
  if (window.getPlatform() === 'gphone') {
    if (window.getCssStyle() === 'black') {
      changeTitleColor(color.white);
    } else {
      changeTitleColor(color.black);
    }
  }
}

function stopBodyScroll(type) {
  const bodyEl = document.body;
  const isFixed = bodyEl.style.position === '';

  if (type && isFixed) {
    bodyEl.setAttribute('scrollY', window.scrollY);
    bodyEl.style.top = `${-window.scrollY}px`;
    bodyEl.style.right = 0;
    bodyEl.style.left = 0;
    bodyEl.style.position = 'fixed';
  } else {
    if (!type && !isFixed) {
      bodyEl.style.position = '';
      bodyEl.style.top = '';
      bodyEl.style.right = '';
      bodyEl.style.left = '';
      const scrollY = parseInt(bodyEl.getAttribute('scrollY'), 10);
      window.scrollTo(0, scrollY);
    }
  }
}

// 根据键值对从数组中取下标
function getItemByKey(obj, key, value) {
  let res = -1;
  for (let i = 0; i < obj.length; i++) {
    if (obj[i][key] === value) {
      res = i;
      break;
    }
  }
  return res;
}

function handleVideoArticleJump(id, type, menuId) {
  const baseUrl = window.location.href.split('#')[0];
  if (type === 1) {
    const link = `${baseUrl}#/coursePlay?id=${id}&menuId=${menuId}`;
    jumpVideoPlayPage(link);
  } else {
    const link = `${baseUrl}#/articlePage?id=${id}`;
    jumpBy2804(link);
  }
}
/**
 * 格式化文章时间
 * @param {string} data 2022-09-09 17:19:15
 * @returns {Promise}
 */
const dealDate = data => {
  const TODIGIT = 1000;
  const DIGIT = 10;
  const HOURS = 3600;
  const MINIT = 60;
  const TWO = 2;
  if (!data) {
    return '';
  }
  // ios时间需要用 / 代替-
  const fixIosDate = data.replace(/\-/g, '/');
  const time = new Date(fixIosDate);
  const dateLine = new Date();
  dateLine.setDate(dateLine.getDate() - TWO);
  const infoDate = new Date(time);
  let res = '';
  if (infoDate > dateLine) {
    let now = new Date();
    now = Date.parse(now);
    const left = (now - time) / TODIGIT;
    const hours = parseInt(left / HOURS, DIGIT);
    let minits = parseInt(left % HOURS / MINIT, DIGIT);
    if (minits === 0) {
      // 最短1分钟
      minits = 1;
    }
    res = hours > 0 ? `${hours}小时前` : `${minits}分钟前`;
  } else {
    res = new Date(time)
      .toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
      })
      .split('/')
      .join('-');
  }
  return res;
};
// 取得与目标时间的时间查（数字）
const getStringTimeDistance = (now, timePoint, isNextDay = false) => {
  const dateStringLength = 10;
  let tartgetTime = null;
  if (isNextDay) {
    const oneDaysss = 86400000;
    tartgetTime = new Date(
      `${new Date(now + oneDaysss).toISOString().slice(0, dateStringLength)} ${timePoint}`
    ).getTime();
  } else {
    tartgetTime = new Date(
      `${new Date(now).toISOString().slice(0, dateStringLength)} ${timePoint}`
    ).getTime();
  }
  return tartgetTime - now;
};
const checkedType = target =>
  Object.prototype.toString
    .call(target)
    .replace(/\[object (\w+)\]/, '$1')
    .toLowerCase();

// 实现深拷贝（Object/Array）
function deepClone(target) {
  let result;
  const type = checkedType(target);
  if (type === 'object') {
    result = {};
  } else if (type === 'array') {
    result = [];
  } else {
    return target;
  }
  for (const key in target) {
    if (checkedType(target[key]) === 'object' || checkedType(target[key]) === 'array') {
      result[key] = deepClone(target[key]);
    } else {
      result[key] = target[key];
    }
  }
  return result;
}

function jsonPase(str) {
  if (!str) {
    return '';
  }
  let res = '';
  try {
    res = JSON.parse(str);
  } catch (error) {
    window.console.error(error);
    window.ClientMonitor.reportFrameErrors(
      {
        // 类型
        category: 'js',
        // 级别
        grade: 'catch',
      },
      error
    );
  }
  return res;
}
export default {
  getOS,
  setTitle,
  androidCanBackProtocol,
  checkLogin,
  jumpToFenShi,
  jumpBy2804,
  jumpVideoPlayPage,
  clientVideo,
  getSearchHistory,
  setTitleColor,
  stopBodyScroll,
  getItemByKey,
  handleVideoArticleJump,
  openPdf,
  dealDate,
  getStringTimeDistance,
  openImg,
  deepClone,
  jsonPase,
};
